package com.yc.springmvc.web;


import com.yc.springmvc.bean.Result;
import com.yc.springmvc.bean.User;
import com.yc.springmvc.biz.BizException;
import com.yc.springmvc.biz.UserBiz;
import com.yc.springmvc.mapper.TestMapper;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;

@RestController
public class UserController {

    @Resource
    TestMapper testMapper;


    // 打开视图
    @RequestMapping("/toReg")
    public ModelAndView toReg(ModelAndView mav){
        mav.setViewName("reg");
        String[] eduItems = {"高中","专科","本科","研究生"};
        mav.addObject("edus", eduItems);
        String[] likeItems = {"篮球","电影","手游","读书"};
        mav.addObject("likes", likeItems);

        mav.addObject("jobs",testMapper.selectJobs());

        return mav;
    }

    @Resource
    UserBiz userBiz;

    @RequestMapping("register")
    public Result register(@RequestBody @Valid User user, Errors errors) throws BizException {
        if(errors.hasErrors()){
            return new Result(0, "字段验证错误", errors.getAllErrors());
        }
        // TODO 调用业务层代码, 保存用户信息
        System.out.println(user);
        userBiz.register(user);
        return new Result(1, "用户注册成功!", null);
    }

    // 头像上传
    @PostMapping("uploadHead")
    public Result uploadHead(@RequestParam("head") MultipartFile head) throws IOException {
        System.out.println("head.getContentType() = " + head.getContentType());
        System.out.println("head.getName() = " + head.getName());
        System.out.println("head.getOriginalFilename() = " + head.getOriginalFilename());
        System.out.println("head.getSize() = " + head.getSize());
        String path = "D:/_文件柜/yc127_129/0724/";
        path += head.getOriginalFilename();
        // 保存文件
        head.transferTo(new File(path));
        // 构建 上传文件的 web 路径
        String webpath = "upload/" + head.getOriginalFilename();
        return new Result(1,"文件上传成功", webpath);
    }

    @RequestMapping("login")
    public ModelAndView login(ModelAndView mav,
                              HttpSession session,
                              @RequestParam("name")
                              String username,
                              @RequestParam("pwd")
                              String password){
        if("yc".equals(username) && "123".equals(password)){
            mav.setViewName("redirect:/mypage.html");
            session.setAttribute("username", username);
        } else {
            mav.setViewName("redirect:/login.html");
        }
        return mav;
    }

}
